package com.imooc.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA224Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Test;

/**
 * 单向加密：消息摘要算法加密
 * @author Administrator
 *
 */
public class ImoocSha {
	private String srcStr = "imooc security sha";
	
	/**
	 * 自带,SHA1
	 */
	@Test
	public void jdkSha1(){
		try {
			MessageDigest md = MessageDigest.getInstance("SHA");
			md.update(srcStr.getBytes());
			//将byte数组转成16进制；
			String sha1Str = Hex.encodeHexString(md.digest());
			System.out.println("JDK SHA1:"+sha1Str);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * BC SHA1的方法
	 */
	@Test
	public void bcSha1(){
		Digest digest = new SHA1Digest();
		digest.update(srcStr.getBytes(), 0, srcStr.getBytes().length);
		byte[] sha1Bytes = new byte[digest.getDigestSize()];
		digest.doFinal(sha1Bytes, 0);
		//将byte数组转成16进制；
		String sha1Str = org.bouncycastle.util.encoders.Hex.toHexString(sha1Bytes);
		System.out.println(" BC SHA1:"+sha1Str);
	}
	/**
	 * BC SHA2：SHA224的方法
	 */
	@Test
	public void bcSha224(){
		Digest digest = new SHA224Digest();
		digest.update(srcStr.getBytes(), 0, srcStr.getBytes().length);
		byte[] sha224Bytes = new byte[digest.getDigestSize()];
		digest.doFinal(sha224Bytes, 0);
		//将byte数组转成16进制；
		String sha224Str = org.bouncycastle.util.encoders.Hex.toHexString(sha224Bytes);
		System.out.println(" BC SHA224:"+sha224Str);
	}
	
	/**
	 * BC SHA2：SHA224的方法
	 */
	@Test
	public void bcSha224_2(){
		try {
			Security.addProvider(new BouncyCastleProvider());
			MessageDigest md = MessageDigest.getInstance("SHA224");
			md.update(srcStr.getBytes());
			//将byte数组转成16进制；
			String sha224Str = Hex.encodeHexString(md.digest());
			System.out.println("方法二： BC SHA224:"+sha224Str);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	/**
	 * CC SHA1:
	 */
	@Test
	public void ccSha1(){
		String sha1 = DigestUtils.sha1Hex(srcStr.getBytes());
		System.out.println("方法一： CC SHA1:"+sha1);
		sha1 = DigestUtils.sha1Hex(srcStr);
		System.out.println("方法二： CC SHA1:"+sha1);
		
	}

}
